# -*- coding: utf-8 -*-
'''
@file: bland_altman.py
@time: 19-2-20 上午10:12
@desc: Bland-Altman分析

'''
from __future__ import division
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def bland_altman(gt_csv, pred_csv, save_dir):
    pred_df = pd.read_csv(pred_csv)
    gt_df = pd.read_csv(gt_csv)
    print(pred_df.head())

    for i, name in enumerate(['lumbar_transverse_diameter-T12', 'lumbar_transverse_diameter-L1', 'lumbar_transverse_diameter-L2',
                              'lumbar_transverse_diameter-L3', 'lumbar_transverse_diameter-L4', 'lumbar_transverse_diameter-L5',]):
        print('\n', i, name)

        pred_value = pred_df.loc[:, ['image_name', name]]
        gt_value = gt_df.loc[:, ['image_name', name]]

        # print pred_value.head()
        all_value = pd.merge(left=pred_value, right=gt_value,how='inner', on='series_uid', suffixes=("_pred", "_gt"))
        ## 去除-1所在的行
        all_value = all_value[~all_value[['{}_pred'.format(name),'{}_gt'.format(name) ]].isin([-1])]

        all_value['mean'] = (all_value['{}_pred'.format(name)] + all_value['{}_gt'.format(name)]) / 2.
        all_value['bias'] = all_value['{}_gt'.format(name)] - all_value['{}_pred'.format(name)]
        print(all_value['bias'].mean())
        print(all_value['bias'].std(), all_value['bias'].std() * 1.96)
        # print all_value

        mean = np.array(all_value['mean'])
        bias = np.array(all_value['bias'])

        ## plot
        plt.figure()

        y = all_value['bias'].mean()
        x_min = all_value['mean'].min()
        x_max = all_value['mean'].max()
        point1, point2 = zip((x_min, y), (x_max, y))
        plt.plot(point1, point2)

        y = all_value['bias'].mean() + all_value['bias'].std() * 1.96
        point1, point2 = zip((x_min, y), (x_max, y))
        plt.plot(point1, point2)

        y = all_value['bias'].mean() - all_value['bias'].std() * 1.96
        point1, point2 = zip((x_min, y), (x_max, y))
        plt.plot(point1, point2)

        ## 0
        y = 0
        point1, point2 = zip((x_min, y), (x_max, y))
        plt.plot(point1, point2, linestyle='--')

        plt.scatter(x=mean, y=bias)
        plt.title('Bland-Altman: {}'.format(name))
        plt.xlabel('mean')
        plt.ylabel('bias')
        plt.minorticks_on()

        pred_dir = os.path.split(pred_csv)[0]
        # measure_dir = os.path.join(pred_dir, 'bland_altman')
        if not os.path.exists(save_dir):
            os.mkdir(save_dir)
        plt.savefig(os.path.join(save_dir, '{}.jpg'.format(name)))

if __name__ == '__main__':
    pass
    s = pd.Series(np.array([1,3,4,6,7]),index = np.array([0,1,2,3,4]))
    s.plot()
    plt.show()